package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        //1.在redis中查找商铺类别
        String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOPTYPE_KEY);
        //2.判断redis中是否命中
        if(StrUtil.isNotBlank(shopTypeJson)){
            //3.命中，将json字符串 转成列表返回
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypeList);
        }

        //4.未命中，去数据库查找
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        //5.数据库无分类信息，返回
        if(shopTypeList==null){
            return Result.fail("无分类！");
        }
        //6.数据库有分类信息，存入redis
        String shopTypeKey=CACHE_SHOPTYPE_KEY;
        stringRedisTemplate.opsForValue().set(shopTypeKey,JSONUtil.toJsonStr(shopTypeList),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //7.返回结果
        return Result.ok(shopTypeList);
    }
}
